package Test.test4.exam3;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

public class ClientTest {
    Socket s = null;
    Scanner sc = null;
    PrintWriter pw = null;
    BufferedReader br = null;

    public ClientTest(Socket s) {
        try {
                pw = new PrintWriter(new OutputStreamWriter(s.getOutputStream()));//用于获取客户端接字的输出流

                    br = new BufferedReader(new InputStreamReader(s.getInputStream()));//用于获取客户端的输出入流
                sc = new Scanner(System.in);

        } catch (IOException e) {
            e.printStackTrace();
        }


}


    public Thread send() {
        return new Thread() {
            @Override
            public void run() {
                while (true) {
                    System.out.println("请输入要向客户端发送的内容");
                    String str = sc.next();//获取向服务器发送的数据
                    pw.println(str);//向服务器端发送数据
                    pw.flush();
                    System.out.println("客户端发送数据成功");
                }
            }
        };

    }

    public Thread receive() {
        return new Thread() {
            @Override
            public void run() {
                try {
                    while (true) {
                        String str = br.readLine();//读取服务端回传的数据
                        System.out.println("服务器传来其它客户端发来的消息:" + str);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        };
    }
    public void close(){
        if(null!=br){
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if(null!=s){
            try {
                s.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if(null!=pw){
            pw.close();
        }
        if(null!=sc){
           sc.close();
        }
    }
}
